﻿using MyCompany.MyProject.Common.Core;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCompany.MyProject.Common.Caches;

/// <summary>
/// 实现 SqlSugar 的 ICacheService 接口
/// </summary>
public class SqlSugarCacheService : ICacheService
{
    private readonly Lazy<ICaching> caching = new(()=>App.GetService<ICaching>(false));
    private ICaching Caching => caching.Value;

    /// <summary>
    /// 添加缓存
    /// </summary>
    /// <typeparam name="V">泛型类型</typeparam>
    /// <param name="key">缓存键</param>
    /// <param name="value">缓存值</param>
    public void Add<V>(string key, V value)
    {
        Caching.Set(key, value);
    }
    /// <summary>
    /// 添加缓存 可以设置过期时间
    /// </summary>
    /// <typeparam name="V">泛型类型</typeparam>
    /// <param name="key">缓存键</param>
    /// <param name="value">缓存值</param>
    /// <param name="cacheDurationInSeconds">过期时间</param>
    public void Add<V>(string key, V value, int cacheDurationInSeconds)
    {
        Caching.Set(key,value,TimeSpan.FromSeconds(cacheDurationInSeconds));
    }
    /// <summary>
    /// 根据 key 判断缓存是否存在
    /// </summary>
    /// <typeparam name="V"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    public bool ContainsKey<V>(string key)
    {
        return Caching.Exists(key);
    }
    /// <summary>
    /// 根据 key 获取泛型缓存值
    /// </summary>
    /// <typeparam name="V"></typeparam>
    /// <param name="key"></param>
    /// <returns></returns>
    public V Get<V>(string key)
    {
        return Caching.Get<V>(key);
    }
    /// <summary>
    /// 获取所有的缓存 key
    /// </summary>
    /// <typeparam name="V"></typeparam>
    /// <returns></returns>
    public IEnumerable<string> GetAllKey<V>()
    {
        return Caching.GetAllCacheKeys();
    }
    /// <summary>
    /// 获取或创建缓存，有就获取，没有就创建
    /// </summary>
    /// <typeparam name="V"></typeparam>
    /// <param name="cacheKey"></param>
    /// <param name="create"></param>
    /// <param name="cacheDurationInSeconds"></param>
    /// <returns></returns>
    public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
    {
        if (!ContainsKey<V>(cacheKey))
        {
            var value = create();
            Caching.Set(cacheKey, value,TimeSpan.FromSeconds(cacheDurationInSeconds));
            return value;
        }
        return Caching.Get<V>(cacheKey);
    }
    /// <summary>
    /// 根据 key 删除缓存
    /// </summary>
    /// <typeparam name="V"></typeparam>
    /// <param name="key"></param>
    public void Remove<V>(string key)
    {
        Caching.Remove(key);
    }
}
